package org.example.io;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Objects;

public class TestCopyContents {
    public static void main(String[] args) throws Exception {
        //源文件夹
        File file = new File("D:\\tmp");
        //目标文件夹
        File file1 = new File("D:\\ddd");
        //调用拷贝方法
        copy(file,file1);
    }

    public static void copy(File file,File file1) throws Exception{

        if(!file1.exists()){
            file1.mkdirs();
        }

        for (File listFile : Objects.requireNonNull(file.listFiles())) {
            if(listFile.isFile()){
                //创建输入流
                FileReader reader = new FileReader(listFile);
                //创建输出流
                FileWriter writer = new FileWriter(new File(file1, listFile.getName()));
                //读取数据
                char[] chars = new char[1024*1024*5];
                int len;
                while ((len=reader.read(chars))!=-1){
                    writer.write(new String(chars,0,len));
                }
                //关闭流
                writer.close();
                reader.close();
            }else{
                copy(new File(file,listFile.getName()),new File(file1,listFile.getName()));
            }
        }
    }
}
